#!/usr/bin/env bash
arch=$(uname -m)
# 设置下载路径
path=/home/gcd/download
# 设置变量
package_manager="apt"
download_tools="wget"
gcd=/usr/bin/gcd # 设置gcd路径
service_name="com.liumou.gcd" # 设置服务名称
service="com.liumou.gcd.service" # 设置服务名称
service_file="/etc/systemd/system/com.liumou.gcd.service" # 设置服务文件路径
mode=install
if [[ $1 == "uninstall" ]];then
  mode=uninstall
elif [[ $1 == "update" ]]; then
  mode=update
fi

GetArch() {
  if [[ $arch == "x86_64" ]];then
    arch="amd64"
  elif [[ $arch == "aarch64" ]];then
    arch="arm64"
  elif [[ $arch == "mips64el" ]]; then
    arch="mips64"
  elif [[ $arch == "armv7l" ]]; then
      arch="arm"
  else
    echo "不支持的架构: ${arch}"
    exit 1
  fi
  ok_list="amd64 arm64 mips64 arm"
  if [[ ! ${ok_list} =~ ${arch} ]];then
    echo "不支持的架构: ${arch}"
    exit 1
  fi
  echo "当前架构: ${arch}"
  url="https://gitee.com/liumou_site/gcd/raw/master/client/gcd_linux-${arch}.bin"
}

url="https://gitee.com/liumou_site/gcd/raw/master/client/gcd_linux-${arch}.bin"

GetPackageManger() {
    which apt >/dev/null 2>&1
    if [[ $? -eq 0 ]];then
      package_manager="apt"
      return
    fi
    which yum >/dev/null 2>&1
    if [[ $? -eq 0 ]];then
      package_manager="yum"
      return
    fi
    which dnf >/dev/null 2>&1
    if [[ $? -eq 0 ]];then
      package_manager="dnf"
      return
    fi
    which zypper >/dev/null 2>&1
    if [[ $? -eq 0 ]];then
      package_manager="zypper"
      return
    fi
    which opkg >/dev/null 2>&1
    if [[ $? -eq 0 ]];then
      package_manager="opkg"
      return
    fi
    echo "不支持的操作系统"
    exit 1
}
CreateUser(){
  if [[ -e /etc/passwd ]];then
    user="gcd"
    group="gcd"
    if [[ -e /etc/group ]];then
      if [[ -z $(cat /etc/group | grep gcd) ]];then
        groupadd gcd
      fi
    else
      groupadd gcd
    fi
    if [[ -z $(cat /etc/passwd | grep gcd) ]];then
      useradd -M -s /bin/false -g gcd gcd
      chmod 700 $gcd
    fi
    # 设置home
    if [[ -e /home/gcd ]];then
      rm -rf /home/gcd
    fi
    mkdir -p ${path}
    chown gcd:gcd /home/gcd
    if [[ -e /etc/ssl/certs/ca-certificates.crt ]];then
      cp -rf /etc/ssl/certs/ca-certificates.crt /home/gcd > /dev/null 2>&1
    fi
  fi
}

# 开始下载gcd
DownloadGcd(){
  echo "开始下载gcd"
  if [[ -e $gcd ]];then
    rm -f $gcd
  fi
  which wget >/dev/null 2>&1
  if [[ $? -eq 0 ]];then
    wget -O $gcd $url
    if [[ $? -ne 0 ]];then
      echo "下载失败 ${url}"
      exit 1
    fi
    echo "下载成功"
    AddExecute
    return
  fi
  which curl >/dev/null 2>&1
  if [[ $? -eq 0 ]];then
    curl -o $gcd $url
    if [[ $? -ne 0 ]];then
      echo "下载失败: ${url}"
      exit 1
    fi
    echo "下载成功"
    AddExecute
    return
  fi
}
# 对执行文件添加可执行权限
AddExecute(){
  if [[ -e $gcd ]];then
    chmod +x $gcd
    return
  fi
  echo "找不到文件: $gcd , 请手动下载"
  exit 3
}

# 检查工具
CheckTools(){
  # 判断工具是否存在
  if [[ -e $gcd ]];then
    rm -f $gcd
  fi
  if [[ -e /usr/bin/wget ]];then
    return
  fi
  if [[ -e /usr/bin/curl ]];then
    return
  fi
  $package_manager install wget -y
  if [[ $? -ne 0 ]];then
    $package_manager install curl -y
    if [[ $? -ne 0 ]];then
      echo "请安装wget或者curl"
      exit 1
    else
      curl -o $gcd $url
      if [[ $? -ne 0 ]];then
        echo "下载失败"
        exit 1
      fi
      return
    fi
  else
    wget -O $gcd $url
    if [[ $? -ne 0 ]];then
      echo "下载失败"
      exit 1
    fi
  fi
}

# 设置定时任务每小时进行服务重启
SetTimer(){
  # 设置定时任务
  if [[ -e /usr/bin/crontab ]];then
    crontab -l > /tmp/crontab.txt
    if [[ -z $(cat /tmp/crontab.txt | grep gcd) ]];then
      echo "0 * * * * systemctl restart com.liumou.gcd > /dev/null 2>&1" >> /tmp/crontab.txt
      crontab /tmp/crontab.txt
    fi
  fi
 }
Config(){
  if [[ $mode == "update" ]];then
    # 仅更新二进制文件,如果service文件不存在则同步更新,如已存在则忽略
    echo "当前模式: ${mode} - 无需重置服务文件"
    # 如果文件已存在则返回,如果不存在则更新
    if [[ -e ${service_file} ]];then
      echo "服务文件已存在,无需重置服务文件"
      return
	fi
	echo "配置文件异常,需要重置服务文件"
  else
    echo "当前模式: ${mode} - 重置服务文件"
  fi
  # 重置服务文件
  if [[ -e ${service_file} ]];then
	systemctl stop ${service_name} > /dev/null 2>&1
	systemctl disable ${service_name} > /dev/null 2>&1
	rm -f ${service_file}
  fi
  chmod +x $gcd
  # 判断输入是否正确，如果不正确则继续输入
  while [[ -z ${key} || -z ${num} ]];do
    read -p "请输入授权码: " key
    read -p "请设置线程数量:" num
    # 判断线程数量是否为数字
    if [[ ! ${num} =~ ^[0-9]+$ ]];then
      echo "线程数量必须为数字"
      num=''
      continue
    fi
  done
  echo "[Unit]
Description=This is a gcd
After=network.target
StartLimitIntervalSec=5

[Service]
Type=simple
User=gcd
ExecStart=${gcd} -k ${key} -t ${num} -s ${path}
StandardOutput=journal
# 终止该服务所有进程
KillMode=control-group
Restart=on-failure
RestartPreventExitStatus=255
StandardError=inherit
SyslogIdentifier=${service_name}

[Install]
WantedBy=multi-user.target
Alias=${service}
"> ${service_file}
  # 显示服务管理命令
  echo "systemctl start ${service_name} # 启动服务"
  echo "systemctl stop ${service_name} # 停止服务"
  echo "systemctl restart ${service_name} # 重启服务"
  echo "systemctl status ${service_name} # 查看服务状态"
  echo "systemctl enable ${service_name} # 设置开机启动"
  echo "systemctl disable ${service_name} # 取消开机启动"
  echo "systemctl is-enabled ${service_name} # 查看是否开机启动"
  # 显示查看日志
  echo "journalctl -u ${service_name} -f # 查看日志"
  exit 0
}
# 服务重载并重启
SetService(){
  systemctl daemon-reload > /dev/null 2>&1
  systemctl restart ${service_name}
  # shellcheck disable=SC2181
  if [[ $? -ne 0 ]];then
    echo "重启失败"
    exit 1
  fi
  # 设置开启
  systemctl enable ${service_name} > /dev/null 2>&1
  echo "重启成功"
}

# 设置时区为上海
SetTimeZone(){
  which timedatectl >/dev/null 2>&1
  if [[ $? -eq 0 ]];then
    timedatectl set-timezone Asia/Shanghai
  fi
}
SetTimeZone # 设置时区为上海
GetArch # 获取架构
GetPackageManger # 获取包管理器
CheckTools # 检查工具
Config # 配置gcd
DownloadGcd # 下载gcd
AddExecute # 添加可执行权限
CreateUser # 创建用户
SetService # 设置服务
SetTimer # 设置定时任务